import { getPlayerData, getVegetableData, isPlayerExist, storagePlayerData } from '../l.js'

const REGULAR = /^(#|\/)?出售(作物|蔬菜)\s*(\S+)(?:\s*\*\s*(\d+))?/
export class Fs extends plugin {
    constructor() {
        super({
            name: '[Fs]出售农作物',
            dsc: '出售农作物',
            event: 'message',
            priority: 1,
            rule: [
                { reg: REGULAR, fnc: 'sellingCrops' },
                { reg: /^(#|\/)?(一键|全部)出售(作物|蔬菜)/, fnc: 'sellAllCrops' }
            ]
        })
    }

    async sellingCrops(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        const [, , , VEGETABLE_NAME, NUMBER] = e.msg.match(REGULAR)
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const VEGETABLE_DATA = await getVegetableData()
        const CROP_DATA = VEGETABLE_DATA.find(crop => crop['name'] === VEGETABLE_NAME)

        if (!CROP_DATA) return e.reply(`未找到名为 ${VEGETABLE_NAME} 的作物`)
        if (!PLAYER_DATA['Stash'][VEGETABLE_NAME]) return e.reply(`您没有 ${VEGETABLE_NAME}，无法出售喵~`)

        const sellAmount = NUMBER ? parseInt(NUMBER) : PLAYER_DATA['Stash'][VEGETABLE_NAME]['number']
        if (isNaN(sellAmount) || sellAmount <= 0) return e.reply('请输入有效的出售数量')
        if (PLAYER_DATA['Stash'][VEGETABLE_NAME]['number'] < sellAmount) return e.reply(`您只有 ${PLAYER_DATA['Stash'][VEGETABLE_NAME]['number']} 个 ${VEGETABLE_NAME}，无法出售 ${sellAmount} 个喵~`)

        const PROFIT = CROP_DATA['salePrice'] * sellAmount

        PLAYER_DATA['Stash'][VEGETABLE_NAME]['number'] -= sellAmount
        PLAYER_DATA['capital'] += PROFIT
        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        return e.reply([
            '出售成功!',
            `出售了 ${sellAmount} 个 ${VEGETABLE_NAME}`,
            `获得💰[${PROFIT}]喵~`
        ].join('\n'))
    }

    async sellAllCrops(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const VEGETABLE_DATA = await getVegetableData()
        let totalProfit = 0
        let soldItems = []

        for (const [cropName, cropInfo] of Object.entries(PLAYER_DATA['Stash'])) {
            const cropData = VEGETABLE_DATA.find(crop => crop['name'] === cropName)
            if (cropData && cropInfo.number > 0) {
                const profit = cropData['salePrice'] * cropInfo.number
                totalProfit += profit
                soldItems.push(`${cropName} x${cropInfo.number}`)
                cropInfo.number = 0
            }
        }

        if (totalProfit === 0) {
            return e.reply('您的仓库中没有可以出售的作物喵~')
        }

        PLAYER_DATA['capital'] += totalProfit
        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        return e.reply([
            '一键出售成功!',
            `出售了以下作物：`,
            ...soldItems,
            `总共获得💰[${totalProfit}]喵~`
        ].join('\n'))
    }
}